using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace CMSWeb.Utility.Difference.DataSources
{
	public class TextLine : IEquatable<TextLine>, IEnumerable<char>
	{
		protected string _text;
		protected string _compareText;
		protected bool _ignoreLeadingWhiteSpace;
		protected bool _ignoreTrailingWhiteSpace;
		protected bool _caseInsensitive;

		protected bool _updating;

		internal TextLine(string text)
			: this(text, false, false, false)
		{
		}

		internal TextLine(bool ignoreLeadingWhiteSpace, bool ignoreTrailingWhiteSpace, bool caseInsensitive)
			: this("", ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, caseInsensitive)
		{
		}

		internal TextLine(string text, bool ignoreLeadingWhiteSpace, bool ignoreTrailingWhiteSpace, bool caseInsensitive)
		{
			_text = text;
			_ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace;
			_ignoreTrailingWhiteSpace = ignoreTrailingWhiteSpace;
			_caseInsensitive = caseInsensitive;

			_updating = false;

			UpdateCompareText();
		}

		protected void UpdateCompareText()
		{
			if ( _updating )
				return;

			// leading whitespace
			int start = 0;
			int length = _text.Length;
			if ( _ignoreLeadingWhiteSpace )
			{
				for ( int i = 0; i < _text.Length; i++ )
				{
					if ( char.IsWhiteSpace(_text, i) )
						start++;
					else
						break;
				}
			}

			// trailing white space
			if ( _ignoreTrailingWhiteSpace )
			{
				for ( int i = _text.Length - 1; i >= 0; i-- )
				{
					if ( char.IsWhiteSpace(_text, i) )
						length--;
					else
						break;
				}
			}

			_compareText = _text.Substring(start, length);

			if ( _caseInsensitive )
				_compareText = _compareText.ToLower();
		}



		#region IEnumerable<char> Members

		public IEnumerator<char> GetEnumerator()
		{
			return _compareText.GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		#endregion

		#region IEquatable<TextLine> Members

		public bool Equals(TextLine other)
		{
			return other._compareText == this._compareText;
		}

		#endregion

		public bool IgnoreLeadingWhiteSpace
		{
			get { return _ignoreLeadingWhiteSpace; }
			set
			{
				_ignoreLeadingWhiteSpace = value;
				UpdateCompareText();
			}
		}

		public bool IgnoreTrailingWhiteSpace
		{
			get { return _ignoreTrailingWhiteSpace; }
			set
			{
				_ignoreTrailingWhiteSpace = value;
				UpdateCompareText();
			}
		}

		public bool CaseSensitive
		{
			get { return _caseInsensitive; }
			set
			{
				_caseInsensitive = value;
				UpdateCompareText();
			}
		}

		public bool Updating
		{
			get { return _updating; }
			set 
			{ 
				_updating = value;
			
				if ( !_updating )
					UpdateCompareText();
			}
		}

	}
}
